

import sys
from distutils.util import get_platform

plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3])
sys.path.append("../build/lib%s" % (plat_specifier))



import jjregion
reload(jjregion)

import pysao
import pysao.funtools
import numpy as np

import funtools_test
import os.path
test_dir = os.path.dirname(funtools_test.__file__)

funtools_makemask = pysao.funtools.make_mask_from_region

import scipy.ndimage as NI

class MaskDiffFuntools(Exception):
    pass

dilatation_structure = np.ones((3,3))

def check_boundary(m1, m2):
    mm = m1 & m2
    boundary_excluded = (~NI.binary_dilation(mm, structure=dilatation_structure)) \
                        | (mm)
    boundary = (m1 - m2) * boundary_excluded
    if boundary.any():
        return False
    else:
        return True
        
def _get_name():
    import itertools
    for _name_num in itertools.count(1):
        yield "t_%02d.reg" % (_name_num)
    
try:
    reg_name_to_save
except:
    reg_name_to_save = _get_name()
    

class funtools_test(object):
    def __init__(self, ):
        """
        """

        self.im = np.zeros([100,120], dtype="d")
        self.ds9 = None

        
    def set_ds9(self, ds9=None):
        self.ds9 = ds9
        
    def check_region(self, reg_string, ds9=None):
        """ Make a mask and compare it to the one using funtools.
        
        Arguments:
        - `reg_name`:
        - `ds9`:
        """
        
        s = reg_string
        
        m1 = funtools_makemask(self.im, s)

        r = jjregion.parse(s)
        m2 = r.mask(self.im.shape)

        ds9 = self.ds9

        if ds9:
            ds9.set("frame 1")
            ds9.view(m1)
            ds9.set("frame 2")
            ds9.view(m2)
            ds9.set("frame 3")
            diff = m1.astype("i") -m2.astype("i")
            ds9.view(diff)

            mm = m1 & m2
            _m1 = ~(NI.binary_dilation(mm))
            boundary_excluded =  _m1 | mm
            boundary = (diff) * boundary_excluded.astype("i")
            ds9.set("frame 4")
            ds9.view(boundary)
            
            ds9.set("frame 1")
            

        if (m1-m2).any():
            if not check_boundary(m1, m2):
                raise MaskDiffFuntools("Generated mask differs significantly from funtools one.")


    def check_regionfile(self, fn):
        s = open(fn).read()
        self.check_region(s)

    def test_regions(self):
        for n in range(1, 10):
            fn = os.path.join(test_dir, "t_%02d.reg" % (n))
            yield self.check_regionfile, fn

    def test_regions2(self):
        n = 10 # bug in funtools?
        fn = os.path.join(test_dir, "t_%02d.reg" % (n))
        try:
            self.check_regionfile(fn)
        except MaskDiffFuntools:
            pass
        

#if __name__ == '__main__':
if 0:
    try:
        ds9
    except:
        ds9 = pysao.ds9()
        ds9.set("tile")
        
        ft = funtools_test()
        ft.ds9 = ds9

        ft.check_regionfile("t_01.reg")


    if 0:
        reg_string = ds9.get("regions")
        ft.check_region(reg_string)
        reg_fname = reg_name_to_save.next()
        print reg_fname
        open(reg_fname,"w").write(reg_string)
        
    #ft.check_regionfile("t_circle1.reg")
    
